<?php 
/**
 * @desc 文件日志记录
 * @author by jason
 * @date 2016-08-26
 * */
namespace Common\Util;

define('DIR_LOGS' , ((defined('ENTRY') && ENTRY)?ENTRY:$_SERVER['DOCUMENT_ROOT']) . '/Logs/');

class Log{
	
	private $filename;
	
	public function __construct($filename) {
		
		if(strpos($filename , '/') == 0){
			
			$this->filename = $filename;
			
		}else{
			
			$this->filename = '/' . $filename;
			
		}
		
	}
	public function write($message , $status = 0 , $data = array() , $unescaped = false) {
		
		$file = DIR_LOGS . $this->filename;
		
		if(!file_exists(dirname($file))){
			
			mkdir( dirname($file) , 0777 , true);
			
		}

		if($unescaped){

			$data = json_encode($data , JSON_UNESCAPED_UNICODE);

		}else{

			$data = json_encode($data);

		}
		
		if($status){
			
			file_put_contents($file , date('Y-m-d G:i:s') . "|SUCCESS|" . iconv('utf-8' , 'gbk' , $message) . '|' . $data . "\r\n" , FILE_APPEND);
			
		}else{
			
			file_put_contents($file , date('Y-m-d G:i:s') . "|ERROR|" . iconv('utf-8' , 'gbk' , $message) . '|' . $data . "\r\n" , FILE_APPEND);
			
		}
		
	}
	private static function encode_json($data) { 
	
		return urldecode(json_encode(self::url_encode($data))); 
		
	}
	private static function url_encode($str) {
		if(is_object($str)){
			$str = (array)$str;
		}  
		if(is_array($str)) {  
			foreach($str as $key=>$value) {  
				$str[urlencode($key)] = $this->url_encode($value);  
			}  
		} else {  
			$str =  urlencode(iconv('utf-8' , 'gbk' , $str));  
		}  
		  
		return $str;  
	}
}